/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.marshaller.decls;

import org.geoscheduler.commons.marshaller.JSONFieldDecl;
import org.geoscheduler.commons.marshaller.JSONMarshaller;
import org.geoscheduler.commons.tools.PropertyDescriptor;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * <h2>JSONAbstractSimpleFieldDecl</h2>
 * <p>
 * Abstract superclass for implementing simple {@link JSONFieldDecl}.
 * </p>
 * 
 * @author lko
 */
public abstract class JSONAbstractSimpleFieldDecl<T> extends JSONAbstractFieldDecl<T> {

	public JSONAbstractSimpleFieldDecl(PropertyDescriptor<T> desc, T defValue) {
		super(desc, defValue);
	}

	public JSONAbstractSimpleFieldDecl(PropertyDescriptor<T> desc) {
		super(desc);
		setDefaultValue(decString(evalDefaultValue(desc)));
	}

	public JSONObject marshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		T val = getDescriptor().getValue(instance);
		obj.put(getJSONName(), encode(encString(val)));
		return obj;
	}

	/** encode value <code>val</code> asString */
	protected abstract String encString(T val);

	/** decode value <code>val</code> from serialized value */
	protected abstract T decString(String strVal);

	public Object unmarshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		if (obj.has(getName())) {
			Object val = obj.getString(getJSONName());
			getDescriptor().setValue(instance, decString((String) val));
		} else {
			getDescriptor().setValue(instance, getDefaultValue());
		}
		return instance;
	}

	protected Object encode(String value) {
		return value == null ? JSONObject.NULL : value;
	}

}
